package com.literature.mlsstart.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import com.literature.mlsstart.service.FileService;
import com.literature.search.core.common.MessageConstant;
import com.literature.search.core.entity.DownloadRecord;
import com.literature.search.core.entity.R.AjaxJson;
import com.literature.search.core.entity.dto.BasePageDTO;
import com.literature.search.core.utils.so.SoMap;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * @ClassName FileServiceImpl
 * @Description TODO
 * @Author abin
 * @Date 2023/3/2 11:36
 * @Version 1.0
 */
public class FileServiceImpl implements FileService {

    private static final String DOWNLOAD_RECORD_COLLECTION_NAME = "download_record"; // 下载记录集合名称: download_record

    @Resource
    MongoTemplate mongoTemplate;

    @Override
    public AjaxJson findDownloadRecordByUserId(BasePageDTO page) {
        Query query = new Query(Criteria.where("id").is(StpUtil.getLoginIdAsString()));
        long count = mongoTemplate.count(query, DownloadRecord.class, DOWNLOAD_RECORD_COLLECTION_NAME);
        if (count < 1) {
            return AjaxJson.getError(MessageConstant.DATA_IS_NULL);
        }
        int pageNum = Optional.ofNullable(page.getPage()).orElse(1);
        int pageSize = Optional.ofNullable(page.getRows()).orElse(10);
        // 如果传入的参数超过了总数，返回第一页
        if ((long) (pageNum - 1) * pageSize > count) {
            pageNum = 1;
        }
        Query query1 = new Query();
        query.skip((long) (pageNum - 1) * pageSize);
        query.limit(pageSize);
        query.with(Sort.by(Sort.Direction.DESC, "createDate"));
        List<DownloadRecord> downloadRecords = mongoTemplate.find(query, DownloadRecord.class, DOWNLOAD_RECORD_COLLECTION_NAME);
        SoMap map = new SoMap();
        map.put("total", count);
        map.put("pageNum", pageNum);
        map.put("pageSize", pageSize);
        map.put("result", downloadRecords);
        return AjaxJson.getSuccessData(map);
    }


}
